<?php
/***************************************************************************
 *
 *   copyright            : (C) 2005 Winds of Storm
 *
 *   $Id: index.php,v 1.36 2007/11/08 20:45:24 amorgan Exp $
 *
 ***************************************************************************/

/***************************************************************************
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 ***************************************************************************/

if (!file_exists("config.php")) {
	die("Please create the configuration file config.php from the example provided or enter the <a href=install/install.php>guided install</a>.");
}

$skip_header	= 1;
$full_header	= 1;
require("config.php");
include($libdir . "init." . $phpEx);
include($libdir . "rooms." . $phpEx);
include($libdir . "chat_functs." . $phpEx);
include($libdir . "login_code." . $phpEx);

function show_login($error) {
	global	$config;
	global	$phpEx;
	global	$body;
	global	$header;

	showHeader($body, $header);
	$template = new Template($config['TPL_DIR']);
	$template->set_filenames(array('body' => 'index_body.tpl'));

	$roomlist	= getRoomList();
	$browserCompat	= array(
				'textmode'	=> MODE_SLIMCHAT,
				'Firefox/1.5'	=> MODE_CLIENT_PULL
			);

	if ($config['CPSP_SLIMCHAT_ENABLED'])	$cpspVals[MODE_SLIMCHAT]		= 'SlimChat';
	if ($config['CPSP_SERVERPUSH_ENABLED'])	$cpspVals[MODE_SERVER_PUSH]		= 'Server Push';
	if ($config['CPSP_CLIENTPULL_ENABLED'])	$cpspVals[MODE_CLIENT_PULL]		= 'Client Pull';
	ksort($cpspVals);

	$cpsp		= $config['DEFAULT_CPSP_VALUE'];

	foreach ($browserCompat as $match => $cpspSel) {
		if (eregi($match, $_SERVER['HTTP_USER_AGENT'])) {
			$cpsp	= $cpspSel;
		}
	}

	if ($DEBUG) {
		$dbgmsg	= "Browsing with: {$_SERVER['HTTP_USER_AGENT']} -- defaulting to {$cpspVals[$cpsp]}.<br />";
	}

	$template->assign_vars(array(
		'ROOMLIST'		=> $roomlist,
		'ERROR'			=> $error,

		'U_WHOSON'		=> "whoson.$phpEx",
		'U_TRANSCRIPTS'		=> "transcripts.$phpEx",

		'USERNAME'		=> $_REQUEST['username'],
		'PASSWORD'		=> $_REQUEST['password'],

		'DEBUG_BROWSER_INFO'	=> $dbgmsg,
		'VERSION'		=> VERSION
	));

	if ($error) {
		$template->assign_block_vars('switch_error', array());
	}

	foreach ($cpspVals as $i => $val) {
		$sel	= '';
		if ($i == $cpsp) {
			$sel	= " SELECTED";
		}
		$template->assign_block_vars('cpsp', array(
			'VALUE'		=> $i,
			'SELECTED'	=> $sel,
			'METHOD'	=> $cpspVals[$i]
		));
	}

	if ($config['ANNOUNCEMENT']) {
		$template->assign_block_vars('switch_show_announce', array(
			'ANNOUNCEMENT'	=> $config['ANNOUNCEMENT']
		));
	}

	$template->pparse('body');
}

if ($config['CHAT_DISABLE'] == 'yes') {
	$body['class']	= 'row2';
	if ($config['CHAT_DISABLE_MSG']) {
		showFatalError($config['CHAT_DISABLE_MSG'], "Notice");
	} else {
		showFatalError("Chat is currently disabled. Please check back later as this may be due to maintainance or other site activity.", "Notice");
	}
}

if ($_REQUEST['op'] && ($_REQUEST['username'] == '' || $_REQUEST['password'] == '')) {
	show_login("Please enter both username and password.");
	exit;
} else if ($_REQUEST['op'] == '') {
	show_login('');
	exit;
}

//
// Check rooms first to pull the mod_group...
//
if ($_REQUEST['dynamic_room'] != '') {
	$sql	= "SELECT * FROM {$dbprefix}rooms WHERE room_name LIKE '{$_REQUEST['dynamic_room']}'";
	$res	= $db->sql_query($sql);

	if (($row = $db->sql_fetchrow($res)) != NULL) {
		$rid	= $row['room_id'];
	} else {
		$dyn_group	= getDynamicGroup();

		$sql	= "INSERT INTO {$dbprefix}rooms (room_name, room_password, room_topic, room_group, room_dynamic) 
				VALUES ('{$_REQUEST['dynamic_room']}', '{$_REQUEST['roompw']}', 'Dynamic room created by {$_REQUEST['username']}', $dyn_group, 'yes')";
		$result = $db->sql_query($sql);
		$rid	= $db->sql_nextid($result);
	}
	$room	= getRoomInfo($rid);
	$rdyn	= 1;
} else {
	if ($_REQUEST['roomlist'] == '') {
		show_login("Please select a valid room.");
		exit;
	}

	$room	= getRoomInfo($_REQUEST['roomlist']);
}

$row		= auth_login($room);
$isMod		= $row['moderator'];
$uid		= $row['user_id'];
$username	= $row['username'];
$board_avatar	= getAvatar($row);
$avatar		= $board_avatar;
addToLog("getAvatar: avatar returned is $board_avatar");


$sql	= "SELECT * FROM {$dbprefix}prefs WHERE user_id=$uid";
//print("<!-- $sql -->\n");
$result = $db->sql_query($sql);
if (($p_row = $db->sql_fetchrow($result)) == NULL) {
	//
	// Create empty prefs if they do not exist already
	//
	$sql	= "INSERT INTO {$dbprefix}prefs (user_id, user_alias) VALUES ($uid, '$username')";
	$result = $db->sql_query($sql);
	$sql	= "INSERT INTO {$dbprefix}aliases (user_id, user_alias, user_avatar) VALUES ($uid, '$username', '$avatar')";
	$result = $db->sql_query($sql);
} else {
	// 
	// Update last login timestamp
	//
	$sql	= "UPDATE {$dbprefix}prefs SET user_lastvisit_chat=UNIX_TIMESTAMP(NOW()) WHERE user_id=$uid";
	$result = $db->sql_query($sql);

	if ($p_row['user_alias'] == '') {
		$sql	= "UPDATE {$dbprefix}prefs SET user_alias='$username' WHERE user_id=$uid";
		$result = $db->sql_query($sql);
	} else {
		$sql	= "SELECT * FROM {$dbprefix}aliases WHERE user_id=$uid AND user_alias LIKE '{$p_row['user_alias']}' AND user_avatar!=''";
		$result = $db->sql_query($sql);
		if (($a_row = $db->sql_fetchrow($result)) != NULL) {
			$avatar	= $a_row['user_avatar'];
		}
	}
}

//
// Make the creator of a dyn room the moderatore of it.
//
if (!$isMod && $rdyn) {
	$isMod	= 1;
	$sql	= "UPDATE {$dbprefix}rooms SET room_creator=$uid WHERE room_id={$room['room_id']}";
	$result = $db->sql_query($sql);
}

// Log out previous sessions
$sql	= "DELETE FROM {$dbprefix}sessions WHERE user_id=$uid AND room_id={$room['room_id']}";
$result = $db->sql_query($sql);

// Create new one
$sid	= getSid();
$sql	= "INSERT INTO {$dbprefix}sessions (session_id, user_id, username, room_id, idle_timer, server_push, moderator, avatar_url, board_avatar_url, user_browser, user_ip) 
		 VALUES('$sid', $uid, '$username', {$room['room_id']}, 0, {$_REQUEST['cpsp']}, $isMod, '$avatar', '$board_avatar', '{$_SERVER['HTTP_USER_AGENT']}', '{$_SERVER['REMOTE_ADDR']}')";
$result = $db->sql_query($sql);

if ($p_row['user_login_msg'] != "") {
	$lmsg	= addslashes($p_row['user_login_msg']);
	$sql    = "INSERT INTO {$dbprefix}events (user_id_from, user_id_to, room_id_to, event_text, event_date, event_chat_flags)
			VALUES ($uid, 0, {$room['room_id']}, '<span class=sysmsg><i>*** $username $lmsg [entering {$room['room_name']}]</i></span>', NOW(), 2)";
} else {
	$sql    = "INSERT INTO {$dbprefix}events (user_id_from, user_id_to, room_id_to, event_text, event_date, event_chat_flags)
			VALUES ($uid, 0, {$room['room_id']}, '<span class=sysmsg><i>*** $username has entered {$room['room_name']}</i></span>', NOW(), 2)";
}
//print($sql);
$result = $db->sql_query($sql);

// Welcome sound
if ($config['SOUNDS_ENABLED']) {
	$sql    = "INSERT INTO {$dbprefix}events (user_id_from, user_id_to, room_id_to, event_text, event_date, event_chat_flags)
			VALUES ($uid, 0, {$room['room_id']}, '{$config['CHAT_URL']}/sounds/welcome.wav', NOW(), 4)";
	$result = $db->sql_query($sql);
}

//
// Logged in, redirect to frameset...
//
Header("Location: main.$phpEx?sid=$sid&cpsp={$_REQUEST['cpsp']}");

?>
